import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {environment} from '../../environments/environment';
import { StorageService } from '../services/storage.service';
import {HandoverobjModel} from './handoverobj.model';

@Injectable()
export class DutyService {
    ip = environment.url.management;
    constructor(private http: HttpClient,
                private storageService: StorageService) {}

    // 获取当日值班数据
    getCurrentDuty() {
        let token = this.storageService.getToken('token');
        return this.http.post(
            `${this.ip}/onduty`,
            {
                'access_token': token,
                'type': 'dutylist_per_get'
            }
        ).map((res: Response) => {
            if (res['errcode'] !== '00000'){
              return [];
            }else{
              this.changeObjectName(res['datas'], 'label', 'post');
            }
            return res['datas'];
        });

    }

    changeObjectName(array, newName, oldName) {
        for (let i in array) {
            array[i][newName] = array[i][oldName];
            delete  array[i][oldName];
            this.changeObjectName( array[i].children, newName, oldName );
        }
    }

//  获取排班管理总数据
    getAllSchduleDatas(name?, status?, page?, pageSize?) {
        (!name) && (name = '');
        (!status) && (status = '');
        (!page) && (page = '1');
        (!pageSize) && (pageSize = '10');

        let token = this.storageService.getToken('token');
        return this.http.post(
            `${this.ip}/onduty`,
            {
                'access_token': token,
                'type': 'duty_get_all',
                'data': {
                    'condition': {
                        'name': name,
                        'status': status
                    },
                    'page': {
                        'page_size': pageSize,
                        'page_number': page
                    }
                }
            }).map((res: Response) => {
            if (res['errcode'] !== '00000'){
              return [];
            }
            return res['data'];

        });
    }

// 获取排班班次
    getAllSchduleShifts() {
        let token = this.storageService.getToken('token');
        return this.http.post(
            `${this.ip}/onduty`,
            {
                'access_token': 'access_tokenxxxxxxxx',
                'type': 'shift_get_all',
                'data': {
                    'status': 'true'
                }
            }
        ).map((res: Response) => {
          if (res['errcode'] !== '00000'){
            throw new Error(res['errmsg']);
          }
          return res['datas'];
        });
    }

//    获取新增计划编号
//     getAddSchduleNumber() {
//         let token = this.storageService.getToken('token');
//         return this.http.post(
//             `${this.ip}/onduty`,
//             {
//                 "access_token": token,
//                 "type": "duty_add_id"
//             }
//         ).map((res: Response) => {
//             let body = res.json();
//             if (body.errcode !== '00000') {
//                 return new Error(body.errmsg);
//             }
//             return body['data'];
//         })
//     }

//    获取关联计划
    getRelaticeScheduleData() {
        let token = this.storageService.getToken('token');
        return this.http.post(
            `${this.ip}/onduty`,
            {
                'access_token': 'access_tokenxxxxxxxx',
                'type': 'duty_relateddid_get',
                'data': {
                    'begin_time': '2017-11-20',
                }
            }
        ).map((res: Response) => {
            // let body = res.json();
            // if (body.errcode !== '00000') {
            //     return new Error(body.errmsg);
            // }
            // return body['datas'];
          if (res['errcode'] !== '00000'){
            throw new Error(res['errmsg']);
          }
          return res['datas'];
        });
    }

//  获取组织树
    getDepartmentDatas(oid?, dep?) {
        (!oid) && (oid = '');
        (!dep) && (dep = '');
        let token = this.storageService.getToken('token');
        return this.http.post(
            `${this.ip}/org`,
            {
                'access_token': token,
                'type': 'get_suborg',
                'id': oid,
                'dep': dep
            }
        ).map((res: Response) => {
          if (res['errcode'] !== '00000'){
            return [];
          }else{
            res['datas'].forEach(function (e) {
                     e.label = e.name;
                     delete e.name;
                     e.leaf = false;
                     e.data = e.name;
                  });
          }
          return res['datas'];
        });
    }

//  获取所有状态种类
    getAllStatus() {
        let token = this.storageService.getToken('token');
        return this.http.post(
            `${this.ip}/onduty`,
            {
                'access_token': 'access_tokenxxxxxxxx',
                'type': 'duty_status_get'
            }
        ).map((res: Response) => {
          if (res['errcode'] !== '00000'){
            return [] ;
          }
          return res['datas'];
        });
    }

//   计划新增接口
    addSchedule(name, ctime, departement, aproval, start, end, shifts, relative, status) {
        // let shiftArray = [];
        // let shiftStr = '';
        // let approvalArray = [];
        // let approvalStr = '';
        (!relative) && (relative = '');
        // shiftStr = this.returnDotString(shifts);
        // approvalStr = this.returnDotString(aproval);
        let token = this.storageService.getToken('token');
        return this.http.post(
            `${this.ip}/onduty`,
            {
                'access_token': token,
                'type': 'duty_save',
                'data': {
                    'did': '',
                    'create_time': ctime,
                    'name': name,
                    'begin_time': start,
                    'end_time': end,
                    'related_duty': relative,
                    'duty_type': '',
                    'attendance_rule': 'true',
                    'approver_structures': aproval,
                    'status': status,
                    'shift_structures': shifts,
                    'orgs_structures': departement
                }
            }
        ).map((res: Response) => {
            // let body = res.json();
            // return body;
            return res;
        });
    }

// 计划修改接口
    editSchedule(id, defaultCreator, name, ctime, departement, aproval, start, end, shifts, relative, status) {

        (!departement) && (departement = '');
        (!relative) && (relative = '');
        let token = this.storageService.getToken('token');
        return this.http.post(
            `${this.ip}/onduty`,
            {
                'access_token': token,
                'type': 'duty_mod',
                'data': {
                    'did': id,
                    'creator': defaultCreator ,
                    'creator_pid': '',
                    'create_time': ctime,
                    'name': name,
                    'begin_time': start,
                    'end_time': end,
                    'related_duty': relative,
                    'duty_type': '',
                    'attendance_rule': '',
                    'shift_change_way': '',
                    'approver': '',
                    'approver_structures': aproval ,
                    'approve_time': '',
                    'approve_remarks': '',
                    'status': status,
                    'shifts': '',
                    'shift_structures': shifts,
                    'template_file_path': '',
                    'schedules': null,
                    'duty_org': '',
                    'orgs_structures': departement,

                }
            }
        ).map((res: Response) => {
            // let body = res.json();
            // if ( body.errcode !== '00000') {
            //     return body.errmsg;
            // }
            // return body.errcode;
          if (res['errcode'] !== '00000'){
            return res['errmsg'];
          }
          return res['errcode'];
        });
    }

    // returnDotString(obj): string {
    //     let array = [];
    //     for( let value of obj) {
    //         if(value.sid){
    //             array.push(value.sid);
    //         }else if(value.pid) {
    //             array.push(value.pid);
    //         }
    //     }
    //     return array.join(',');
    // }

//  通过ID获取计划接口
    getScheduleById(id) {
        let token = this.storageService.getToken('token');
        return this.http.post(
            `${this.ip}/onduty`,
            {
                'access_token': token,
                'type': 'duty_get',
                'id': id
            }
        ).map((res: Response) => {
           // let body = res.json();
           // if (body.errcode !== '00000') {
           //     return  body['errmsg'];
           // }
           // return body['data'];
          if (res['errcode'] !== '00000'){
            throw new Error(res['errmsg']);
          }
          return res['data'];
        });
    }

//    下载模板
    downloadModel(id) {
        let token = this.storageService.getToken('token');
        return this.http.post(
            `${this.ip}/onduty`,
            {
                'access_token': token,
                'type': 'duty_download',
                'id': id
            }
        ).map((res: Response) => {
            // let body = res.json();
            // if (body.errcode !== '00000') {
            //     return  false;
            // }
            // return body['data'];
          if (res['errcode'] !== '00000'){
            return false;
          }
          return res['data'];
        });
    }

//  删除计划
    deleteSchedule(id) {
        let token = this.storageService.getToken('token');
        return this.http.post(
            `${this.ip}/onduty`,
            {
                'access_token': token,
                'type': 'duty_del',
                'ids': id
            }
        ).map((res: Response) => {
            // let body = res.json();
            // if (body.errcode !== '00000') {
            //     return  body.errmsg;
            // }
            // return body.errcode;
          if (res['errcode'] !== '00000'){
            return res['errmsg'];
          }
          return res['errcode'];
        });
    }

//    审批接口
    approveSchedule(id, remarks, status){
        let token = this.storageService.getToken('token');
        return this.http.post(
            `${this.ip}/onduty`,
            {
                'access_token': token,
                'type': 'duty_audit',
                'data': {
                    'did': id,
                    'approve_remarks': remarks,
                    'status': status
                }
            }
        ).map((res: Response) => {
            // let body = res.json();
            // if (body.errcode !== '00000') {
            //     return  false;
            // }
            // return true;
          if (res['errcode'] !== '00000'){
            return false;
          }
          return true;

        });
    }

//    调班日志总览
    getALLshiftsLog(did?, pre?, current?, number?, size?) {
        (!did) && (did = '');
        (!pre) && (pre = '');
        (!current) && (current = '');
        (!number) && (number = '1');
        (!size) && (size = '10');

        let token = this.storageService.getToken('token');
        return this.http.post(
            `${this.ip}/onduty`,
            {
                'access_token': token,
                'type': 'shiftchange_get_all',
                'data': {
                    'condition': {
                        'did_name': did,
                        'pre_per_name': pre,
                        'operator_name': current
                    },
                    'page': {
                        'page_size': size,
                        'page_number': number
                    }
                }
            }
        ).map((res: Response) => {
            // let body = res.json();
            // if (body.errcode !== '00000') {
            //     return  false;
            // }
            // return body['data'];
          if (res['errcode'] !== '00000'){
            return false;
          }
          return res['data'];
        });
    }

//    班次设置总览接口（下拉）
    getAllshiftSetting(size?, number?) {
        (!number) && (number = '1');
        (!size) && (size = '10');

        let token = this.storageService.getToken('token');
        return this.http.post(
            `${this.ip}/onduty`,
            {
                'access_token': token,
                'type': 'shift_get_all',
                'data': {
                    'status': '启用'
                }
            }
        ).map((res: Response) => {
            // let body = res.json();
            // if (body.errcode !== '00000') {
            //     return  false;
            // }
            // return body['datas'];
          if (res['errcode'] !== '00000'){
            return false;
          }
          return res['datas'];
        });
    }

//    班次有分页的总览接口
    getAllShiftQuery(number?, size?){
        (!number) && (number = '1');
        (!size) && (size = '10');

        let token = this.storageService.getToken('token');
        return this.http.post(
            `${this.ip}/onduty`,
            {
                'type': 'shift_query',
                'data': {
                    'condition': {
                        'status': ''
                    },
                    'page': {
                        'page_size': size,
                        'page_number': number
                    }
                }
            }
        ).map((res: Response) => {

          if (res['errcode'] !== '00000'){
            return false;
          }
          return res['data'];
        });
    }

//    获取值班总览接口
    getAllDuty(begin, end){
        let token = this.storageService.getToken('token');
        return this.http.post(
            `${this.ip}/onduty`,
            {
                'access_token': token,
                'type': 'dutylist_get',
                'data': {
                    'begin_time': begin,
                    'end_time': end
                }
            }
        ).map((res: Response) => {
            // let body = res.json();
            // if (body.errcode !== '00000') {
            //     return  [];
            // }
            // return body['datas'];
          if (res['errcode'] !== '00000'){
            return [];
          }
          return res['datas'];
        });
    }

//    获取可调班人员接口
    getPremissionPerson(did, pre) {
        let token = this.storageService.getToken('token');
        return this.http.post(
            `${this.ip}/onduty`,
            {
                'access_token': token,
                'type': 'shiftchange_get_per',
                'data': {
                    'did': did,
                    'pre_per': pre
                }
            }
        ).map((res: Response) => {
            // let body = res.json();
            // if (body.errcode !== '00000') {
            //     return  false;
            // }
            // return body['datas'];
          if (res['errcode'] !== '00000'){
            return false;
          }
          return res['datas'];
        });
    }

//    调班新增接口
    addShift(did, sid, bt, pp, ppn, cp, cpn){
        let token = this.storageService.getToken('token');
        return this.http.post(
            `${this.ip}/onduty`,
            {
                'access_token': token,
                'type': 'shiftchange_add',
                'data': {
                    'did': did,
                    'sid': sid,
                    'begin_time_1': bt,
                    'pre_per': pp,
                    'pre_per_name': ppn,
                    'cur_per': cp,
                    'cur_per_name': cpn
                }
            }
        ).map((res: Response) => {
          if (res['errcode'] !== '00000'){
            return false;
          }
          return true;
        });
    }

//    新增班次
    addDiyShift( obj) {
        let token = this.storageService.getToken('token');
        return this.http.post(
            `${this.ip}/onduty`,
            {
                'access_token': token,
                'type': 'shift_add',
                'data': {
                    'sid': obj['sid'],
                    'name': obj['name'],
                    'shift_type': obj['shift_type'],
                    'begin_time_1': obj['begin_time_1'],
                    'end_time_1': obj['end_time_1'],
                    'begin_time_2': obj['begin_time_2'] ,
                    'end_time_2': obj['end_time_2'],
                    'overall_time': obj['overall_time'],
                    'color': obj['color'],
                    'status': obj['status']
                }
            }
        ).map((res: Response) => {
          if (res['errcode'] !== '00000'){
            return res['errmsg'];
          }
          return res['errcode'];
        });
    }

//    编辑班次
    editDiyShift( obj) {
        let token = this.storageService.getToken('token');
        return this.http.post(
            `${this.ip}/onduty`,
            {
                'access_token': token,
                'type': 'shift_mod',
                'data': {
                    'sid': obj['sid'],
                    'name': obj['name'],
                    'shift_type': obj['shift_type'],
                    'begin_time_1': obj['begin_time_1'],
                    'end_time_1': obj['end_time_1'],
                    'begin_time_2': obj['begin_time_2'] ,
                    'end_time_2': obj['end_time_2'],
                    'overall_time': obj['overall_time'],
                    'color': obj['color'],
                    'status': obj['status']
                }
            }
        ).map((res: Response) => {
            if (res['errcode'] !== '00000'){
                return res['errmsg'];
            }
            return res['errcode'];
        });
    }
    //   冻结或解冻班次
    freezeOrUnfreezeDiyShift( obj) {
        let token = this.storageService.getToken('token');
        return this.http.post(
            `${this.ip}/onduty`,
            {
                'access_token': token,
                'type': 'shift_mod_status',
                'data': {
                    'sid': obj['sid'],
                    'status': obj['status']
                }
            }
        ).map((res: Response) => {
            if (res['errcode'] !== '00000'){
                return res['errmsg'];
            }
            return res['errcode'];
        });
    }
    //   删除班次
    deletDiyShift( array: Array<any>) {
        let token = this.storageService.getToken('token');
        return this.http.post(
            `${this.ip}/onduty`,
            {
                'access_token': token,
                'type': 'shift_del',
                'ids': array

            }
        ).map((res: Response) => {
            if (res['errcode'] !== '00000'){
                return res['errmsg'];
            }
            return res['errcode'];
        });
    }


    //  获取登录用户当前值班信息
    getUserDutyMsg() {
        let token = this.storageService.getToken('token');
        return this.http.post(
            `${this.ip}/onduty`,
            {
                'access_token': token,
                'type': 'dutylist_get_byowner_now'
            }
        ).map((res: Response) => {
            if (res['errcode'] !== '00000'){
                return res['errmsg'];
            }
            return res;
        });
    }
    //  获取下一次值班人员
    getNextDutyPerson() {
        let token = this.storageService.getToken('token');
        return this.http.post(
            `${this.ip}/onduty`,
            {
                'access_token': token,
                'type': 'dutylist_nextshift_per_get'
            }
        ).map((res: Response) => {
            if (res['errcode'] !== '00000'){
                return res['errmsg'];
            }
            return res;
        });
    }
    //   新增交接班
    addHandover( obj) {
        let token = this.storageService.getToken('token');
        return this.http.post(
            `${this.ip}/onduty`,
            {
                'access_token': token,
                'type': 'shiftexchange_add',
                'data': {
                    'sid': obj['sid'],
                    'shift_id': obj['shift_id'],
                    'shiftexchange_type': obj['shiftexchange_type'],
                    'acceptor': obj['acceptor'],
                    'acceptor_pid': obj['acceptor_pid'],
                    'accept_time': obj['accept_time'],
                    'content': obj['content'],
                    'remarks': obj['remarks'],
                    'shift_time': obj['shift_time'],
                    'shift_name': obj['shift_name']
                }
            }
        ).map((res: Response) => {
            if (res['errcode'] !== '00000'){
                return res['errmsg'];
            }
            return res['errcode'];
        });
    }
  //   获取交接班总览接口
  getHandoverOverView(obj: Object) {
    let token = this.storageService.getToken('token');
    return this.http.post(
      `${this.ip}/onduty`,
      {
        'access_token': token,
        'type': 'shiftexchange_get',
        'data': {
          'condition': {
            'sid': obj['sid'],
            'creator': obj['creator'],
            'acceptor': obj['acceptor'],
            'status': obj['status']
          },
          'page': {
            'page_size': obj['page_size'],
            'page_number': obj['page_number']
          }
        }
      }
    ).map((res: Response) => {
      if (res['errcode'] !== '00000'){
        return [];
      }
      return res['data'];
    });
  }
  //   接受或拒绝交接班
  acceptOrRejectHandover( obj) {
    let token = this.storageService.getToken('token');
    return this.http.post(
      `${this.ip}/onduty`,
      {
        'access_token': token,
        'type': 'shiftexchange_accept',
        'data': {
            'sid': obj['sid'],
            'status': obj['status'],
            'accept_remarks': obj['accept_remarks']
        }
      }
    ).map((res: Response) => {
      if (res['errcode'] !== '00000'){
        return res['errmsg'];
      }
      return res['errcode'];
    });
  }
  //   保存交接班
  saveHandover( obj) {
    let token = this.storageService.getToken('token');
    return this.http.post(
      `${this.ip}/onduty`,
      {
        'access_token': token,
        'type': 'shiftexchange_save',
        'data': {
            'sid': obj['sid'],
            'shiftexchange_type': obj['shiftexchange_type'],
            'shift_id': obj['shift_id'],
            'acceptor': obj['acceptor'],
            'acceptor_pid': obj['acceptor_pid'],
            'content': obj['content'],
            'remarks': obj['remarks'],
            'shift_time': obj['shift_time'],
            'shift_name': obj['shift_name']
        }
      }
    ).map((res: Response) => {
      if (res['errcode'] !== '00000'){
        return res['errmsg'];
      }
      return res['errcode'];
    });
  }
  //   删除交接班
  deletHandover( array) {
    let token = this.storageService.getToken('token');
    return this.http.post(
      `${this.ip}/onduty`,
      {
        'access_token': token,
        'type': 'shiftexchange_del',
        'ids': array
      }
    ).map((res: Response) => {
      if (res['errcode'] !== '00000'){
        return res['errmsg'];
      }
      return res['errcode'];
    });
  }
    //   获得交接班所有状态
    getHandoverStatus() {
        let token = this.storageService.getToken('token');
        return this.http.post(
            `${this.ip}/onduty`,
            {
                'access_token': token,
                'type': 'shiftexchange_statuslist_get'
            }
        ).map((res: Response) => {
            if (res['errcode'] !== '00000'){
                return [];
            }
            return res;
        });
    }
    //   获取交接班带我处理
    getMineHandover(obj: object) {
        let token = this.storageService.getToken('token');
        return this.http.post(
            `${this.ip}/onduty`,
            {
                'access_token': token,
                'type': 'shiftexchange_get_byowner',
                'data': {
                    'condition': {
                        'status': obj['status']
                    },
                    'page': {
                        'page_size': obj['page_size'],
                        'page_number': obj['page_number']
                    }
                }
            }
        ).map((res: Response) => {
            if (res['errcode'] !== '00000'){
                return [];
            }
            return res['data'];
        });
    }
}
